package eshttp

import (
	"crypto/md5"
	"fmt"
	"net/http"
	"strings"

	"gitee.com/les49/esgo/constant"
	"gitee.com/les49/esgo/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
)

type FileUploadReq struct {
	Md5  string `json:"md5,optional" form:"md5,optional"`
	Name string `json:"name,optional" form:"name,optional"`
	Size uint32 `json:"size,optional" form:"size,optional"`
}

func GetUploadData(r *http.Request) (*FileUploadReq, []byte, error) {
	var req FileUploadReq
	var err error
	if err = httpx.ParseForm(r, &req); err != nil {
		return nil, nil, err
	}

	err = r.ParseMultipartForm(constant.HTTP_FORM_FILE_MAX_SIZE)
	if err != nil {
		logx.Info(err)
		return nil, nil, err
	}

	file, header, err := r.FormFile("file")
	if err != nil {
		logx.Info(err)
		return nil, nil, err
	}
	defer file.Close()

	if len(req.Name) <= 0 {
		req.Name = header.Filename
		req.Size = uint32(header.Size)
	}

	b := make([]byte, header.Size)
	_, err = file.Read(b)
	if err != nil {
		logx.Info(err)
		return nil, nil, errors.FileTooLarge
	}

	if len(req.Md5) > 0 {
		md5 := fmt.Sprintf("%x", md5.Sum(b))
		if !strings.EqualFold(md5, req.Md5) {
			return nil, nil, errors.FileMd5Check
		}

	}
	return &req, b, nil
}
